//
//  UIView+ABCDynamic.m
//  ABCAppearanceKit_Example
//
//  Created by mac on 2022/9/1.
//  Copyright © 2022 Joe. All rights reserved.
//

#import "NSObject+ABCDynamic.h"
#import <objc/runtime.h>


@implementation NSObject (ABCDynamic)


- (void)setUpdateDynamicList:(NSArray<ABCUpdateDynamicBlock> *)updateDynamicList {
    objc_setAssociatedObject(self, @selector(updateDynamicList), updateDynamicList, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSArray<ABCUpdateDynamicBlock> *)updateDynamicList {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)abc_bindDynamicUpdate:(ABCUpdateDynamicBlock)updateDynamic {
    if (!updateDynamic) {
        return;
    }
    
    updateDynamic(ABCDynamicManager.currentDynamicStyle);
    
    if ([self.updateDynamicList containsObject:updateDynamic]) {
        return;
    }
    NSMutableArray *array  = [[NSMutableArray alloc]init];
    if (self.updateDynamicList) {
        [array addObjectsFromArray:self.updateDynamicList];
    }
    [array addObject:updateDynamic];
    self.updateDynamicList = [array copy];
    [[ABCDynamicUpdater sharedInstance] abc_addDynamicTarget:self];
}

- (void)abc_unBindDynamicUpdate:(ABCUpdateDynamicBlock)updateDynamic {
    if (!updateDynamic || !self.updateDynamicList) {
        return;
    }
    if ([self.updateDynamicList containsObject:updateDynamic]) {
        NSMutableArray *array  = [NSMutableArray arrayWithArray:self.updateDynamicList];
        [array removeObject:updateDynamic];
        self.updateDynamicList = [array copy];
    }
    if (self.updateDynamicList.count == 0) {
        [[ABCDynamicUpdater sharedInstance] abc_removeDynamicTarget:self];
    }
}

- (void)abc_unBindAllDynamicUpdate {
    if (self.updateDynamicList.count == 0) {
        return;
    }
    self.updateDynamicList = nil;
    [[ABCDynamicUpdater sharedInstance] abc_removeDynamicTarget:self];
}

@end
